package org.budo.accesslog.servlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.budo.accesslog.interceptor.AbstractAccesslogInterceptor;
import org.budo.support.mvcs.Mvcs;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Slf4j
@Getter
@Setter
public class BudoAccesslogServletFilter extends AbstractAccesslogInterceptor implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        this.beforeAccess();

        Throwable error = null;
        try {
            chain.doFilter(request, response);
        } catch (Throwable e) {
            error = e; // 有异常
        }

        // 后处理, 写记录
        Mvcs.setError(error);
        this.afterAccess();

        // 如果有异常，抛出
        this.throwError(error, request);
    }

    @Override
    public void destroy() {
        log.info("#37 destroy, this=" + this);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("#28 init, this=" + this);
    }
}